package pab.core.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;

import pab.core.exception.TransactionException;
import pab.core.transaction.Currency;
import pab.core.webservicex.CurrencyConvertor;
import pab.core.webservicex.CurrencyConvertorSoap;


public class WebExchangeRate implements ExchangeRate {

	private final List<Currency> supportedCurrencies = new ArrayList<Currency>();
	private CurrencyConvertorSoap soap;
	
	private final Map<String, Currency> currencyMap = new HashMap<String, Currency>();
	
	public WebExchangeRate() throws TransactionException {
		
		for (pab.core.webservicex.Currency c : pab.core.webservicex.Currency.values()) {
			Currency currency = new Currency(c.name(), c.getName());
			supportedCurrencies.add(currency);
			currencyMap.put(c.name(), currency);
		}
		
		//check if the web service works fine
		try {
			soap = new CurrencyConvertor().getCurrencyConvertorSoap();
			
			soap.conversionRate(pab.core.webservicex.Currency.fromValue("USD"), 
					pab.core.webservicex.Currency.fromValue("VND"));
		} catch (Exception e) {
			throw new TransactionException(e);
		}

	}
	
	public double exchangeRate(Currency fromCurreny, Currency toCurrency) {
		
		if (fromCurreny.getCode().equals(toCurrency.getCode())) {
			return 1.0;
		}
		
		double rate = soap.conversionRate(pab.core.webservicex.Currency.fromValue(fromCurreny.getCode()), 
									pab.core.webservicex.Currency.fromValue(toCurrency.getCode()));
		if (rate != 0) {
			return rate; 
		} else {
			return 1.0 / soap.conversionRate(pab.core.webservicex.Currency.fromValue(toCurrency.getCode()), 
					pab.core.webservicex.Currency.fromValue(fromCurreny.getCode()));
		}
	}

	public List<Currency> getSupportedCurrencies() {
		return supportedCurrencies;
	}
	
	public Currency getCurrency(String code) {
		return currencyMap.get(code);
	}
	
	public static void main(String[] args) throws Exception {
		WebExchangeRate ex = new WebExchangeRate();
		System.out.println(25000 * 1.0 / ex.exchangeRate(ex.supportedCurrencies.get(3), ex.supportedCurrencies.get(0)));
		
	}

}
